import React, { useEffect, useState } from 'react'
import { Form, Button, message, Popconfirm, Modal, Select, Row, Col, Input, DatePicker } from 'antd'
import { connect } from 'umi'
import {SearchOutlined} from '@ant-design/icons';
import SelectUserModal from "@/pages/components/SelectUserModal";
import {findEmployeeSalaryGroupById, getSalaryGroupList} from '../../service'
import {salaryAdjustmentTypeList} from "@/utils/constant";

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const formLayout = {
  labelCol: { span: 5 },
};

const CreateForm = (props) => {
  const { onSubmit, onCancel, current, visible, salaryGroup, payrollUnit, operateType } = props;
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [userInfo, setUserInfo] = useState(null);

  useEffect(()=>{
    if (visible && current){
      let salaryGroupId = current && current.oidSalaryGroupId;
      let payrollUnitId = current && current.oidPayrollUnitId;
      form.setFieldsValue({salaryGroupId, payrollUnitId});
    }
  },[visible]);

  const confirmSelectUser = (info) => {
    if (info) {
      let needsUserInfo ={
        name: info[0].name,
        oid: info[0].oid,
      };
      setUserInfo(needsUserInfo);
      getSalaryGroupList(info[0].code).then(res => {
        if (res.flag){
          if (res.data){
            form.setFieldsValue({...needsUserInfo, salaryGroupId: res.data.groupId, payrollUnitId: res.data.payUnitId});
          }else {
            form.setFieldsValue(needsUserInfo);
          }
        }
      });
      setUserModalVisible(false);
    } else {
      message.error('请选择人员!')
    }
  };

  const showSelectUserModal = () =>{
    setUserModalVisible(true);
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
  };

  const onFormCancel = () => {
    form.resetFields();
    setUserInfo(null);
    onCancel()
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    if (operateType === 'update'){
      onSubmit({
        ...fieldsValue,
        oid: current.oid,
        id: current.id
      })
    }else {
      onSubmit({
        ...fieldsValue,
        ...userInfo
      })
    }
    setUserInfo(null);
  };

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
        {
          operateType === 'add' ?
            <>
              <Col span={0}>
                <FormItem name="applyCode" label="申请人工号" >
                  <Input disabled={true}/>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem name="name" label="姓名" rules={[{required: true, message: '姓名不能为空'}]}>
                  <Input.Group compact size="large">
                    <Input style={{ width: '80%',height: '32px', fontSize:'14px', background: '#ffffff' }} placeholder="选择员工" value={userInfo ? userInfo.name : ''} disabled={true}/>
                    <Button style={{ width: '20%' }} icon={<SearchOutlined/>} onClick={() => showSelectUserModal()} />
                  </Input.Group>
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem name="type" label="变动类型" rules={[{required: true, message: '变动类型不能为空'}]}>
                <Select placeholder="请选择">
                  {salaryAdjustmentTypeList.map((item, index) => {
                    return (
                      <Option value={`${item.value}`} key={item.value}>
                        {item.label}
                      </Option>
                    )
                  })}
                </Select>
                </FormItem>
              </Col>
            </> : ''

        }
          <Col span={12}>
            <FormItem name="salaryGroupId" label="薪资组" rules={[{ required: true, message: '请选择要分配的薪资组！' }]}>
              <Select placeholder="请选择薪资组" showSearch className='widthStyle' filterOption={filterOption}>
                {salaryGroup != null?salaryGroup.map((item, index) => {
                  return (
                    <Option value={`${item.coidGroup}`} key={item.coidGroup}>
                      {item.cname}
                    </Option>
                  )
                }) : []}
              </Select>
            </FormItem>

          </Col>
          <Col span={12}>
            <FormItem name="payrollUnitId" label="发薪单位" rules={[{ required: true, message: '请选择要分配的发薪单位！' }]}>
              <Select placeholder="请选发薪单位" showSearch className='widthStyle' filterOption={filterOption}>
                {payrollUnit.map((item, index) => {
                  return (
                    <Option value={`${item.coidOrgunit}`} key={item.coidOrgunit}>
                      {item.cname}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem name="distributionTime" label="分配时间" rules={[{ required: true, message: '请选择分配时间！' }]}>
              <DatePicker placeholder="请选择日期" style={{ width: '100%' }}/>
            </FormItem>
          </Col>
          {
            operateType !== 'add' && current && current.type === 3 ?<Col span={12}>
              <FormItem name="hiredate" label="入职时间">
                <div>{current.hiredate}</div>
              </FormItem>
            </Col> : null
          }
          {/*<Col span={12}>
            <FormItem name="isTax" label="是否节税" rules={[{ required: true, message: '请选择是否节税！' }]}>
              <Select placeholder="请选是否节税" showSearch className='widthStyle'>
                <Option value={0}>否</Option>
                <Option value={1}>是</Option>
              </Select>
            </FormItem>
          </Col>*/}
          {
            operateType === 'add' ?
              <Col span={12}>
                <FormItem name="remark" labelCol={{span: 5}} label="说明"
                          rules={[{required: true, message: '说明不能为空！'}]}>
                  <TextArea rows={4}/>
                </FormItem>
              </Col> : null
          }

        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Popconfirm title={`是否确认该分配操作?`}
                    onConfirm={handleSubmit}
                    okText="是"
                    cancelText="否">
          <Button type="primary">提交</Button>
        </Popconfirm>
      </>
    )
  };

  return (
    <Modal
      width={900}
      destroyOnClose
      title="薪资组分配"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>

      <SelectUserModal
        selectType={0}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />

    </Modal>
  )
};


export default connect(({ global }) => ({
  global,
}))(CreateForm)
